package top.serms.leetcode;


import java.util.Arrays;

/**
 * @Author: SerMs
 * @Date: 2023/09/07 20 22
 * @Email: 1839928782@qq.com
 * @Blog: https://serms.top
 * 求arr[L...R]，范围上有序  归并排序,O(nLongN)
 **/

public class Code01_MergeSort {

    public static void main(String[] args) {
        int[] arr = {2, 1, 3, 4, 1, 2, 6, 3};
        int[] process = process(arr, 0, arr.length - 1);
        Arrays.stream(process).forEach(System.out::println);
    }


    public static int[] process(int[] arr, int l, int r) {
        if (l == r) {
            return arr;
        }
        // 求出mid
        int mid = l + ((r - l) >> 1);
        process(arr, l, mid);
        process(arr, mid + 1, r);
        return merge(arr, l, mid, r);
    }


    private static int[] merge(int[] arr, int l, int mid, int r) {
        int[] help = new int[r - l + 1];
        int i = 0;  // help 指针
        int p1 = l;
        int p2 = mid + 1;
        while (p1 <= mid && p2 <= r) {
            help[i++] = arr[p1] <= arr[p2] ? arr[p1++] : arr[p2++];
        }
        while (p1 <= mid) {
            help[i++] = arr[p1++];
        }
        while (p2 <= r) {
            help[i++] = arr[p2++];
        }
        for (i = 0; i < help.length; i++) {
            arr[l + i] = help[i];
        }

        return arr;
    }


}
